package cn.itcast.mq.config;

import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.retry.MessageRecoverer;
import org.springframework.amqp.rabbit.retry.RepublishMessageRecoverer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author Xiao
 * @version 1.0
 * @description 配置异常消息交换机队列
 * @date 2021/11/19
 */
@Configuration
public class ErrorMessageConfig {
    /**
     * 定义异常接收消息的交换机、队列 -- 失败策略
     */
    private static final String ERROR_EXCHANGE = "error.direct";
    private static final String ERROR_QUEUE = "error.queue";
    private static final String ERROR_TEST_KEY = "error.test";
    @Bean
    public DirectExchange errorMessageExchange() {
        return new DirectExchange(ERROR_EXCHANGE);
    }
    @Bean
    public Queue errorMessageQueue() {
        return QueueBuilder.durable(ERROR_QUEUE).build();
    }
    @Bean
    public Binding errorQueueBinding() {
        return BindingBuilder.bind(errorMessageQueue()).to(errorMessageExchange()).with(ERROR_TEST_KEY);
    }
    /**
     * 定义RepublishMessageRecoverer
     *      消息接收失败后将消息投递到一个指定的，专门存放异常消息的队列，后续由人工集中处理。
     * @param rabbitTemplate
     * @return
     */
    @Bean
    public MessageRecoverer messageRecoverer(RabbitTemplate rabbitTemplate) {
        return new RepublishMessageRecoverer(rabbitTemplate, ERROR_EXCHANGE, ERROR_TEST_KEY);
    }
}
